// pages/recipesDetails/recipesDetails.js
const app = getApp();
const Controller = require('../controllers/controllers.js').controller;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    recipeId: '',
    inputval:'',
    recipedetail: null,
    page: 1,
    pageSize: 10,
    commentlist: [],
    lastPage: false,
    isUser: false,
    userId: '',
    comment: '',
    isfocus:false,
    isloading:true,
    parentId:'',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (options.id) {
      this.setData({
        recipeId: options.id
      })
    }
    if(options.parentid){
      app.globalData.parentid=options.parentid
    }
    if (options.title) {
      wx.setNavigationBarTitle({
        title: options.title
      })
    }
    app.globalData.isRefresh = false
  },

  //输入
  input(e) {
    this.setData({
      comment: e.detail.value
    });
  },

  vip(e){
    wx.navigateTo({
      url:"/pages/Me/vip"
    });
  },
  formatRichText(html) {
    if(html){
      let newContent = html.replace(/<img[^>]*>/gi, function(match, capture) {
        match = match.replace(/style="[^"]+"/gi, '').replace(/style='[^']+'/gi, '');
        match = match.replace(/width="[^"]+"/gi, '').replace(/width='[^']+'/gi, '');
        match = match.replace(/height="[^"]+"/gi, '').replace(/height='[^']+'/gi, '');
        return match;
      });
      newContent = newContent.replace(/<table[^>]*>/gi, function(match, capture) {
        match = match.replace(/style="[^"]+"/gi, '').replace(/style='[^']+'/gi, '');
        match = match.replace(/width="[^"]+"/gi, '').replace(/width='[^']+'/gi, '');
        match = match.replace(/height="[^"]+"/gi, '').replace(/height='[^']+'/gi, '');
        return match;
      });
      newContent = newContent.replace(/style="[^"]+"/gi, function(match, capture) {
        match = match.replace(/width:[^;]+;/gi, 'max-width:100%;vertical-align:middle;')
        return match;
      });
      // newContent = newContent.replace(/<br[^>]*\/>/gi, '');
      newContent = newContent.replace(/\<img/gi,
        '<img style="max-width:100%;vertical-align:middle;"');
      return newContent;
    }
  },
  //支付 1是名医，2是专家，3.养生视频，4养生资讯
  pay() {
    if(app.globalData.isios){
      wx.showToast({
        title:"ios提示不能支付",
        icon:"none"
      })
      return
    }
    wx.navigateTo({
      url:"/pages/mall/order?ordertype=5&id="+this.data.recipeId+"&type=recipe&source=食谱"
    });
  },

  zan(e){
    var _self=this;
    if(this.data.recipedetail.hasLike==0){
      this.action(1,true)
    }else{
      wx.showModal({
        title: '提示',
        content: '是否取消点赞',
        success:(res)=>{
          if (res.confirm) {
            _self.action(1,false)
          } else if (res.cancel) {
          }
        }
      })
    }
  },

  action(type,isbool){
    var data={}
    if(isbool){
      data.rId=this.data.recipeId
      data.type=type  //类型，1是点赞，2是关注，3.浏览,5分享，6发布,7.签到8.观看视频
      data.source=6  // 主体对象的类型，1是名医内容，2是专家内容，3.养生视频，4养生资讯，5是商城，6食谱，7名医，8专家
      data.contentType=3  //内容类型，1是文章，2是视频，3是食谱，4.课程，5是商品
      Controller.action(data).then(res=>{
        if(type==1 && isbool){
          wx.showToast({
            title:"点赞成功"
          })
          this.getRecipedetail()
        }
      })
    }else{
      data.actionId=this.data.recipedetail.likeActionId
      Controller.delAction(data).then(res=>{
          wx.showToast({
            title:"取消成功"
          })
          this.getRecipedetail()
      })
    }
  },


  //评论
  submit() {
    if (this.data.comment == "") {
      wx.showToast({
        title: '请输入评论内容',
        icon: 'none',
        duration: 1200
      });
      return
    }
    Controller.comment({
      bodyType: 6,
      bodyId: this.data.recipeId,
      level:this.data.isUser?2:1,
      toUserId:this.data.isUser?this.data.userId:'',
      content:this.data.comment,
      parentId:this.data.parentId
    }).then(res=>{
      if(res.code==0){
        wx.showToast({
          title: res.msg,
          icon: 'success',
          duration: 1200
        });
        this.setData({
          isUser:false,
          userId:'',
          comment:'',
          commentlist:[]
        })
        this.getCommentlist()
      }
    })
  },

  //评论用户
  comment(e){
    let userId = e.currentTarget.dataset["id"]
    let userNick = e.currentTarget.dataset["usernick"]
    let parentId=e.currentTarget.dataset.parentid
    this.setData({
      isUser:true,
      userId,
      userNick,
      parentId,
      isfocus:true
    })
  },



  //获取食谱详情
  getRecipedetail() {
    Controller.recipedetail({
      recipeId: this.data.recipeId
    }).then(res => {
      if (res.code == 0) {
        let list = []
        let stuff = []
        let imgUrls = []
        let recipedetail = res.data.baseData
        if (recipedetail.ingredients) {
          if (recipedetail.ingredients.indexOf(',') != -1) {
            list = recipedetail.ingredients.split(',')
          } else {
            list = [recipedetail.ingredients]
          }
          list.forEach(element => {
            stuff.push({
              title: element.split('-')[0],
              text: element.split('-')[1]
            })
          });
          recipedetail.stuff = stuff
        }
        if(recipedetail.imgUrls){
          if(recipedetail.imgUrls.indexOf(',') != -1){
            imgUrls = recipedetail.imgUrls.split(',')
          }else{
            imgUrls = [recipedetail.imgUrls]
          }
          recipedetail.imgUrls = imgUrls
        }
        recipedetail.way = this.formatRichText(recipedetail.way)
        recipedetail.effects = this.formatRichText(recipedetail.effects)
        this.setData({
          recipedetail
        })
        wx.setNavigationBarTitle({
          title: this.data.recipedetail.title
        })

        if(this.data.isloading){
          this.action(3,true)
          
        }
      }
      this.setData({
        isloading:false
      })
    })
  },
  //获取评论列表
  getCommentlist() {
    Controller.commentlist({
      bodyType: 6,
      bodyId: this.data.recipeId,
      page: this.data.page,
      pageSize: this.data.pageSize
    }).then(res => {
      if (res.code==0) {
        let commentlist = this.data.commentlist
        commentlist = commentlist.concat(res.data.baseData.list)
        console.log('commentlist',commentlist)
        this.setData({
          commentlist,
          lastPage: res.data.baseData.lastPage
        })
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getRecipedetail()
    this.getCommentlist()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if(this.data.lastPage){
      return
    }
    this.setData({
      page:this.data.page+1
    })
    this.getCommentlist()
  },
  onShareAppMessage: function (e) {
    let title = '';
    let imageUrl = '';
    let path=app.getCurrentPageUrlWithArgs()
    let obj = {
      title,
      imageUrl,
      path,
      success: function (res) {},
      fail(err) {}
    }
    this.action(5,true)
    return obj
  },
  onShareTimeline: function(res){
    let title = '';
    let imageUrl = '';
    let path=app.getCurrentPageUrlWithArgs()
    let obj = {
      title,
      imageUrl,
      path,
      success: function (res) {},
      fail(err) {}
    }
    this.action(5,true)
    return obj
  },
  
})